import { html, PageComponent } from 'nvagir'

import './Settings.less'

/**
 * 用于生成设置页面组件
 *
 * @returns 设置页面组件
 */
const Settings: PageComponent = () => {
  /**
   * 存储设置列表信息的数据结构
   */
  type SettingsFormData = {
    avatarUrl: string
    userName: string
    gender: string
    bday: string
    region: string
    college: string
    userIntro: string
  }

  /**
   * 将现有设置项数据填入对应位置
   */
  const initFormData = function (): void {
    let formData: SettingsFormData = JSON.parse(
      localStorage.getItem('userSettings')!,
    )
    if (formData) {
      doms.previewImage.src = formData.avatarUrl
      doms.userNameInput.setAttribute('value', formData.userName)
      if (formData.gender === 'male') {
        doms.maleInput.checked = true
      } else if (formData.gender === 'female') {
        doms.femaleInput.checked = true
      }
      doms.bdayInput.setAttribute('value', formData.bday)
      doms.regionSelect.value = formData.region
      doms.collegeInput.setAttribute('value', formData.college)
      doms.userIntroText.value = formData.userIntro
    }
  }

  /**
   * 返回按钮点击事件处理函数
   */
  const backBtnClickHandler: EventListener = function () {
    history.back()
  }

  /**
   * 上传头像的事件处理函数
   *
   * @param this 指代调用该函数的对象
   */
  const uploadAvatar: EventListener = function (this: HTMLInputElement) {
    const file = this.files![0]
    let temp = doms.previewImage.src
    doms.previewImage.src = file ? URL.createObjectURL(file) : temp
  }

  /**
   * 更新按钮点击事件
   *
   * @remarks
   * 更新用户数据，这里暂没有使用网络传输，数据将被写入本地存储
   */
  let timerId: number = 0
  const saveBtnClick: EventListener = e => {
    e.preventDefault()

    let formData: SettingsFormData = {
      avatarUrl: '',
      userName: '',
      gender: '',
      bday: '',
      region: '',
      college: '',
      userIntro: '',
    }

    formData.avatarUrl = doms.previewImage.src
    formData.userName = doms.userNameInput.value
    if (doms.maleInput.checked) {
      formData.gender = 'male'
    } else if (doms.femaleInput.checked) {
      formData.gender = 'female'
    }
    formData.bday = doms.bdayInput.value
    formData.region = doms.regionSelect.value
    formData.college = doms.collegeInput.value
    formData.userIntro = doms.userIntroText.value

    localStorage.setItem('userSettings', JSON.stringify(formData))
    // 控制台输出数据
    console.log(formData)

    // 提示文字的动画效果
    doms.savedTip.classList.add('show-saved-tip')
    timerId = setTimeout(function () {
      clearTimeout(timerId)
      doms.savedTip.classList.remove('show-saved-tip')
    }, 8000)
  }

  const { el, doms } = html<{
    previewImage: HTMLImageElement
    userNameInput: HTMLInputElement
    maleInput: HTMLInputElement
    femaleInput: HTMLInputElement
    bdayInput: HTMLInputElement
    regionSelect: HTMLSelectElement
    collegeInput: HTMLInputElement
    userIntroText: HTMLTextAreaElement
    savedTip: HTMLElement
  }>`
    <div class="settings">
      <div class="settings-con">
        <div class="back-btn" n@click=${backBtnClickHandler}>
          <i class="iconfont-class icon-back"></i>
        </div>
        <h1 class="settings-header">个人设置</h1>
        <form class="edit-form">
          <div class="edit-list">
            <div class="info-input">
              <div class="info-item">
                <label class="info-item-label" for="user-name">昵称</label>
                <input
                  type="text"
                  id="user-name"
                  placeholder="填写你的昵称"
                  required
                  maxlength="20"
                  value="defaultName"
                  n@name="userNameInput"
                />
              </div>
              <div class="info-item">
                <label class="info-item-label">性别</label>
                <div class="gender-input-con">
                  <label>
                    <input
                      type="radio"
                      name="sex"
                      value="male"
                      n@name="maleInput"
                    />男
                  </label>
                  <label>
                    <input
                      type="radio"
                      name="sex"
                      value="female"
                      n@name="femaleInput"
                    />女
                  </label>
                </div>
              </div>
              <div class="info-item">
                <label class="info-item-label" for="birthday">生日</label>
                <input id="birthday" type="date" n@name="bdayInput" />
              </div>
              <div class="info-item">
                <label class="info-item-label" for="region">地区</label>
                <select id="region" name="provinces" n@name="regionSelect">
                  <option value="">---</option>
                  <option value="hebei">河北省</option>
                  <option value="shanxi">山西省</option>
                  <option value="liaoning">辽宁省</option>
                  <option value="jilin">吉林省</option>
                  <option value="heilongjiang">黑龙江省</option>
                  <option value="jiangsu">江苏省</option>
                  <option value="zhejiang">浙江省</option>
                  <option value="anhui">安徽省</option>
                  <option value="fujian">福建省</option>
                  <option value="jiangxi">江西省</option>
                  <option value="shandong">山东省</option>
                  <option value="henan">河南省</option>
                  <option value="hubei">湖北省</option>
                  <option value="hunan">湖南省</option>
                  <option value="guangdong">广东省</option>
                  <option value="hainan">海南省</option>
                  <option value="sichuan">四川省</option>
                  <option value="guizhou">贵州省</option>
                  <option value="yunnan">云南省</option>
                  <option value="shannxi">陕西省</option>
                  <option value="gansu">甘肃省</option>
                  <option value="qinghai">青海省</option>
                  <option value="taiwan">台湾省</option>
                  <option value="neimenggu">内蒙古自治区</option>
                  <option value="guangxi">广西壮族自治区</option>
                  <option value="xizang">西藏自治区</option>
                  <option value="ningxia">宁夏回族自治区</option>
                  <option value="xinjiang">新疆维吾尔自治区</option>
                  <option value="beijing">北京市</option>
                  <option value="tianjin">天津市</option>
                  <option value="shanghai">上海市</option>
                  <option value="chongqing">重庆市</option>
                  <option value="hongkong">香港特别行政区</option>
                  <option value="aomen">澳门特别行政区</option>
                </select>
              </div>
              <div class="info-item">
                <label class="info-item-label" for="college">院校</label>
                <input
                  id="college"
                  type="text"
                  placeholder="填写你的院校"
                  maxlength="50"
                  n@name="collegeInput"
                />
              </div>
              <div class="info-item">
                <label class="info-item-label" for="user-intro">简介</label>
                <textarea
                  id="user-intro"
                  placeholder="填写你的职业技能，擅长的事情，喜欢的事情等"
                  maxlength="100"
                  value="defaultIntro"
                  n@name="userIntroText"
                ></textarea>
              </div>
            </div>

            <div class="avatar-input">
              <label for="upload-avatar">
                <div class="avatar-mask">
                  <i class="iconfont-class icon-add"></i>
                  <span class="click-text">点击更换头像</span>
                </div>
                <img
                  src="https://placekitten.com/200/200"
                  alt="preview-img"
                  n@name="previewImage"
                />
              </label>
              <input
                id="upload-avatar"
                type="file"
                accept="image/jpg, image/jpeg, image/png"
                n@change=${uploadAvatar}
              />
              <div class="avatar-text">我的头像</div>
            </div>
          </div>

          <div class="save-btn-con">
            <button class="save-btn" n@click=${saveBtnClick}>更新</button>
            <div class="saved-tip" n@name="savedTip">更新成功</div>
          </div>
        </form>
      </div>
    </div>
  `

  initFormData()

  return { el }
}

export default Settings
